package top.ysh.controller;

import top.ysh.service.UserService;
import top.ysh.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/*
    此servlet 的主要作用是获取请求，解析要执行的方法名称
    抽取出方法，在DemoServlet执行功能

 */
public class BaseServlet extends HttpServlet {
    // 定义service层对象
    UserService userService = null;

    @Override
    public void init() throws ServletException {
        // 初始化中实现实现类
        userService = new UserServiceImpl();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("..................");
        // 1.获取URI
        String uri = req.getRequestURI();
        // System.out.println(uri); // /baseServlet/demo/login
        // 截取请求中最后一个请求方法
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);
        // System.out.println(methodName); //login

        // 反射
        // System.out.println(this);  // top.ysh.controller.DemoServlet@47441bbe

        // 获取执行的方法对象
        try {
            Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            // System.out.println(method);  // public void top.ysh.controller.DemoServlet.login(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
            // 执行方法
            method.setAccessible(true);
            method.invoke(this,req,resp);
        } catch (Exception e) {
            e.printStackTrace();

        }

    }
}
